package com.ruoyi.aitcommon.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitapp.utils.*;
import com.ruoyi.aitapp.vo.APPFormVO;
import com.ruoyi.aitapp.vo.BarcodeConfigVO;
import com.ruoyi.aitapp.vo.UserRunTimeVO;
import com.ruoyi.aitcommon.anotation.ApiLog;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.service.SQLService;
import com.ruoyi.aitcommon.utils.*;
import com.ruoyi.aitcommon.vo.PageDataVO;
import com.ruoyi.aitcommon.vo.PageInfoVO;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * AIT APP API
 */
@RestController
@RequestMapping("/ait/common/app")
public class APPOperation {
    @Autowired
    ConfigManager configManager;
    @Autowired
    APPConfigUtils appConfigUtils;
    @Autowired
    APPFormUtils appFormUtils;
    @Autowired
    APPDataUtils appDataUtils;
    @Autowired
    SQLService sqlService;
    @Autowired
    BarcodeConfigUtils barcodeConfigUtils;
    @Autowired
    RedisCache redisCache;
    @Autowired
    APPRuntimeManager appRuntimeManager;
    @ApiLog("获取通知条数")
    @PostMapping("/getNotification")
    public JSONObject getNotification(@RequestBody String jsonstr) {
        try{
            final JSONObject json = JSONUtils.parseObject(jsonstr);
            final String userCode = json.getString("userCode");
            ExceptionUtils.checkBlankOrUndefined(userCode,"userCode 为空");
            int cnt=appRuntimeManager.getUserApproveCnt(userCode);
            return JSONResult.success(cnt);
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }
    /**
     * 条码打印
     * @param jsonstr
     */
    @ApiLog("条码打印")
    @PostMapping("/barcodePrint")
    public JSONObject barcodePrint(@RequestBody String jsonstr) {
        try{
            final JSONObject json = JSONUtils.parseObject(jsonstr);
            final BarcodeConfigVO config = barcodeConfigUtils.getConfig();
            barcodeConfigUtils.printBarcode(config, json);
            return JSONResult.success();
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }
    /**
     * 单据保存
     * @param jsonstr
     */
    @ApiLog("单据保存至ERP")
    @PostMapping("/erpSave")
    public JSONObject erpSave(@RequestBody String jsonstr) {
        try{
            final JSONObject json = JSONUtils.parseObject(jsonstr);
            ExceptionUtils.checkBlankOrUndefined(json.getString("pageCode"),"pageCode 为空");
            ExceptionUtils.checkBlankOrUndefined(json.get("datas"),"datas 为空");
            final JSONArray datas = json.getJSONArray("datas");
            final APPFormVO formVO = appFormUtils.getAppFormVO(json.getString("pageCode"),datas.get(0));
            final Object ret = appFormUtils.saveFormData(formVO, json.getJSONArray("datas"));
            final JSONObject ret1 = JSONUtils.getJSONObjectByObject(ret);
            return JSONResult.success(ret1);
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }

    /**
     * 获取U9附件
     * @param jsonstr
     */
    @ApiLog("获取U9附件")
    @PostMapping("/getU9Attachment")
    public JSONObject getU9Attachment(@RequestBody String jsonstr) {
        try{
            //调用U9服务,获取U9返回文件清单
            final JSONObject json = JSONUtils.parseObject(jsonstr);
            ExceptionUtils.checkBlankOrUndefined(json.getString("pageCode"),"pageCode 为空");
            ExceptionUtils.checkBlankOrUndefined(json.get("datas"),"datas 为空");
            final JSONArray datas = json.getJSONArray("datas");
            final APPFormVO formVO = appFormUtils.getAppFormVO(json.getString("pageCode"),datas.get(0));
            //调用U9单据接口,获取U9返回文件清单
            //文件保存在U9临时目录中
            final JSONArray fileList = (JSONArray)appFormUtils.saveFormData(formVO, json.getJSONArray("datas"));
            //临时目录中存在多个附件,基于传入文件名,进行文件清单过滤,匹配具体文件信息
            ExceptionUtils.checkBlankOrUndefined(fileList,"文件清单为空");
            JSONObject retJSON1 = new JSONObject();
            for(Object file:fileList){
                final JSONObject fileJson = (JSONObject) file;
                final String fileName = fileJson.getString("FileName");
                final String attaName = datas.getJSONObject(0).getString("attaName");
                if(fileName.equals(attaName)){
                    retJSON1=fileJson;
                    //从app参数获取
                    final JSONObject erpFileServer = appConfigUtils.getAPPParamsJson("erpFileServer");
                    //添加绝对路径
                    String absUrl=erpFileServer.getString("url")+fileJson.getString("Url");
                    retJSON1.put("absUrl", absUrl);
                }
            }
            ExceptionUtils.checkBlankOrUndefined(retJSON1,"未找到文件");
            return JSONResult.success(retJSON1);
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }

    /**
     * 条码解析
     * @param jsonstr
     */
    @ApiLog("条码解析")
    @PostMapping("/barcodeParse")
    public JSONObject barcodeParse(@RequestBody String jsonstr) {
        try{
            final BarcodeConfigVO config = barcodeConfigUtils.getConfig();
            final JSONObject data = JSONUtils.parseObject(jsonstr);
            final Map<String, Object> barData = barcodeConfigUtils.parseBarcodeConfig(config, data);
            return JSONResult.success(barData);
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }
    /**
     * 获取上下文配置
     * @param parm 参数,举例:appconfig.menus
     */
    @ApiLog("获取JSON配置")
    @GetMapping("/parm")
    public JSONObject parm(String parm) {
        try{
            Object retObj = configManager.getContextByParm(parm,false);
            return JSONResult.success(retObj);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    /**
     * 保存上下文配置
     * @param parm 参数,举例:appconfig.menus
     * @param parmBody 配置内容,JSON格式
     */
    @ApiLog("保存JSON配置")
    @PostMapping("/parm")
    public JSONObject saveParm(String parm, @RequestBody String parmBody) {
        try{
            Object json=JSONUtils.parseJSON(parmBody);
            configManager.saveContextByParm(parm,(JSON) json);
            return JSONResult.success();
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    /**
     * 获取上下文配置
     * 基于Key从JSONArray中过滤
     * @param parm 参数,举例:appconfig.menus
     * @param fieldName JSONArry中的Key字段名称
     * @param fieldValue 匹配值
     */
    @ApiLog("保存JSON配置")
    @GetMapping("/parmArray")
    public JSONObject getParmArray(String parm,String fieldName, String fieldValue) {
        try{
            final Object array = configManager.getContextByParm(parm);
            if(!(array instanceof JSONArray)){
                ExceptionUtils.throwException(null, "参数[{}]不是JSONArray!", parm);
            }
            final JSONObject jsonObject = JSONUtils.FindJSONArray((JSONArray) array, fieldName, fieldValue);
            return JSONResult.success(jsonObject);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    /**
     * 保存上下文配置
     * 基于Key保存到JSONArray中
     * @param parm 参数,举例:appconfig.menus
     * @param fieldName JSONArry中的Key字段名称
     * @param isDelete 是否删除,默认=false
     * @param parmBody 配置内容,JSON格式
     */
    @ApiLog("保存JSON配置")
    @PostMapping("/parmArray")
    public JSONObject saveParmArray(String parm,String fieldName,
            @RequestParam(value = "isDelete", defaultValue = "false") Boolean isDelete,
            @RequestBody String parmBody) {
        try{
            Object json=JSONUtils.parseJSON(parmBody);
            configManager.saveContextArrayByParm(parm,fieldName,(JSON) json,isDelete);
            //更新APP参数后,重构参数
            if(appConfigUtils.isAppParam(parm)){
                appConfigUtils.buildParam();
            }
            return JSONResult.success();
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }

    @ApiLog("APP通用查询接口")
    @PostMapping("/APPQuery")
    public JSONObject APPQuery(@RequestBody String jsonstr) {
        List<Map<String, Object>> retlist = null;
        try {
//			参数校验
            ExceptionUtils.checkBlankOrUndefined(jsonstr, "传入参数为空");
            JSONObject json = JSONObject.parseObject(jsonstr);
            String table = json.getString("table");
            ExceptionUtils.checkBlankOrUndefined(table, "table为空");
            String dbstr = json.getString("db");
            String path = json.getString("path");
//            获取DB数据集合
            retlist = sqlService.getDBData(dbstr,table, path);
//          基于retlist做二次过滤
            String filter = json.getString("filter");
            if (ObjUtils.isNotBlank(filter)) {
                List<Map<String, Object>> filteredList = ListMapUtils.MapFilter(retlist, filter);
                retlist = filteredList; // 更新retlist为过滤后的结果
            }
            return JSONResult.success(retlist);
        } catch (Exception ex) {
            return JSONResult.error(ex.getMessage());
        }
    }

    @ApiLog("APP分页查询接口")
    @PostMapping("/PageQuery")
    public JSONObject PageQuery(@RequestBody String jsonstr) {
        try {
//			参数校验
            ExceptionUtils.checkBlankOrUndefined(jsonstr, "传入参数为空");
            JSONObject json = JSONObject.parseObject(jsonstr);
            //获取参数
            final JSONObject pageInfo = json.getJSONObject("pageInfo");
            PageInfoVO pageInfoVO=JSONObject.toJavaObject(pageInfo, PageInfoVO.class);
            //处理分页查询
            final PageDataVO retData = appDataUtils.queryERPByParam(json.getString("view"),
                    json.getString("path"),"", pageInfoVO);
            //处理返回
            return JSONResult.success(retData);
        } catch (Exception ex) {
            return JSONResult.error(ex.getMessage());
        }
    }

    /**
     * 传入page对象,返回页面详情和数据
     * @param jsonstr page对象
     * @return
     */
    @ApiLog("APP页面数据详情查询接口")
    @PostMapping("/PageDataInfoQuery")
    public JSONObject PageDataInfoQuery(@RequestBody String jsonstr) {
        try {
            final JSONObject jsonObject = JSONUtils.parseObject(jsonstr);
            ExceptionUtils.checkBlankOrUndefined(jsonObject.get("code"),"code为空");
            final String pageCode = jsonObject.getString("code");
//            依据页面code获取APPFormVO
            APPFormVO appFormVO = appFormUtils.getAppFormVO(pageCode,jsonObject.get("params"));
//            依据传入参数,设置 FORM VIEW 数据
            appFormVO=appFormUtils.setFormViewData(jsonObject.get("code").toString(),jsonObject.get("params"), appFormVO);
//            更新用户信息
            final JSONObject params = jsonObject.getJSONObject("params");
            if(ObjUtils.isNotBlank(params)){
                final String userCode = params.getString("username");
                if(ObjUtils.isNotBlank(userCode)){
                    final UserRunTimeVO userInfo = appRuntimeManager.initUserInfo(userCode);
                    final Map<String, Object> pageMap = appConfigUtils.getPage(pageCode);
                    userInfo.setLastPageCode(pageCode);
                    userInfo.setLastPageName(pageMap.get("name").toString());
                    appRuntimeManager.updateUserInfo(userInfo);
                }
            }

//            处理返回
            return JSONResult.success(appFormVO);
        }catch (Exception ex){
            return JSONResult.error(ex);
        }
    }
}
